package ru.vsu.cs.pm.pages;

import org.apache.wicket.extensions.markup.html.tree.table.ColumnLocation;
import org.apache.wicket.extensions.markup.html.tree.table.IColumn;
import org.apache.wicket.extensions.markup.html.tree.table.PropertyRenderableColumn;
import org.apache.wicket.extensions.markup.html.tree.table.PropertyTreeColumn;
import org.apache.wicket.feedback.ComponentFeedbackMessageFilter;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.*;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;
import ru.vsu.cs.pm.BasePage;
import ru.vsu.cs.pm.PMSession;
import ru.vsu.cs.pm.beans.AccountManager;
import ru.vsu.cs.pm.beans.DealerShipManager;
import ru.vsu.cs.pm.beans.ItemManager;
import ru.vsu.cs.pm.components.tree.MutableTreeNode;
import ru.vsu.cs.pm.components.tree.MutableTreeTable;
import ru.vsu.cs.pm.models.*;

import javax.swing.tree.DefaultTreeModel;
import java.util.List;

/**
 * User: Oleg
 * Date: 08.01.2011
 * Time: 22:52:42
 */
public class DealerShipPage extends BasePage {
    @SpringBean
    private DealerShipManager dealerShipManager;

    @SpringBean
    private AccountManager accountManager;

    @SpringBean
    private ItemManager itemManager;

    private MutableTreeTable tree;

    private ItemType itemType;

    public DealerShipPage(ItemType itemType) {
        this(new DealerShip(), itemType);
    }

    public DealerShipPage(DealerShip dealerShip, ItemType itemType) {
        this(new DealerShipModel(dealerShip), itemType);
    }

    public DealerShipPage(DealerShipModel dealerShipModel, ItemType itemType) {
        this.itemType = itemType;
        boolean isNewDealerShip = dealerShipModel.getObject().getId() == null;
        String title = this.itemType == ItemType.INCOME ? "Income" : "Expense";
        add(new Label("incomeMessage", isNewDealerShip ? "Add new " + title : "Edit the " + title));
        add(new DealerShipForm("incomeForm", dealerShipModel));
    }

    private class DealerShipForm extends Form<DealerShip> {

        public DealerShipForm(String id, IModel<DealerShip> dealerShipIModel) {
            super(id, new CompoundPropertyModel<DealerShip>(dealerShipIModel));

            // account drop down
            List<Account> accountsList = getAccountsList();
            DropDownChoice<Account> accountFromField = new DropDownChoice<Account> ("accountFrom", accountsList,
                    new ChoiceRenderer<Account> () {
                        @Override
                        public Object getDisplayValue(Account object) {
                            return object.getTitle();
                        }
                        @Override
                        public String getIdValue(Account object, int index) {
                            return Integer.toString(index);
                        }
                    });
            add(accountFromField);
            accountFromField.setVisible(DealerShipPage.this.itemType == ItemType.EXPENSE);

            DropDownChoice<Account> accountToField = new DropDownChoice<Account> ("accountTo", accountsList,
                    new ChoiceRenderer<Account> () {
                        @Override
                        public Object getDisplayValue(Account object) {
                            return object.getTitle();
                        }
                        @Override
                        public String getIdValue(Account object, int index) {
                            return Integer.toString(index);
                        }
                    });
            add(accountToField);
            accountToField.setVisible(DealerShipPage.this.itemType == ItemType.INCOME);

            //item table
            IColumn[] columns = new IColumn[] {
                new PropertyTreeColumn(new ColumnLocation(ColumnLocation.Alignment.MIDDLE, 8, ColumnLocation.Unit.PROPORTIONAL),
                        "Title", "userObject.title"),
                new PropertyRenderableColumn(new ColumnLocation(ColumnLocation.Alignment.MIDDLE, 8, ColumnLocation.Unit.PROPORTIONAL), "Description",
                        "userObject.description"),
            };
            MutableTreeNode rootNode = new MutableTreeNode();
            List<Item> rootItems = itemManager.getRootItemsForUserByType(PMSession.get().getAuthenticatedUser(),
                            DealerShipPage.this.itemType);
            MutableTreeNode child = null;
            for (Item item : rootItems) {
                child = new MutableTreeNode(item);
                child.setAllowsChildren(item.getChildrenCount() > 0);
                rootNode.add(child);
            }
            DefaultTreeModel model = new DefaultTreeModel(rootNode);
            model.setAsksAllowsChildren(true);
            tree = new MutableTreeTable("item", new Model(model), columns);
            tree.setRootLess(true);
            add(tree);

            // description field
            TextField<String> descriptionField = new TextField<String> ("description");
            descriptionField.setRequired(true);
            add(descriptionField);

            // money field
            TextField<Long> moneyField = new TextField<Long>("money");
            moneyField.setRequired(true);
            add(moneyField);

            //feedback panel
            add(new FeedbackPanel("incomeFeedback"/*, new ComponentFeedbackMessageFilter(this)*/));

            //cancel button
            Button cancelButton = new Button("cancelButton") {
                @Override
                public void onSubmit() {
                    setRedirect(true);
                    setResponsePage(MoneyTransferListPage.class);
                }
            };
            cancelButton.setDefaultFormProcessing(false);
            add(cancelButton);
        }

        @Override
        protected void onSubmit() {
            DealerShip dealerShip = this.getModelObject();
            User user = PMSession.get().getAuthenticatedUser();

            if (dealerShip.getAccountFrom() == null && dealerShip.getAccountTo() == null) {
                error("Please select account");
                return;
            }

            if (!tree.getTreeState().getSelectedNodes().isEmpty()) {
                MutableTreeNode treeNode = (MutableTreeNode) tree.getTreeState().getSelectedNodes().iterator().next();
                if (treeNode != null) {
                    Item item = (Item) treeNode.getUserObject();
                    dealerShip.setItem(item);
                    if (itemType == ItemType.INCOME) {
                        dealerShipManager.addIncome(dealerShip, user);
                    } else if (itemType == ItemType.EXPENSE) {
                        dealerShipManager.addExpense(dealerShip, user);
                    }
                    setRedirect(true);
                    setResponsePage(MoneyTransferListPage.class);
                } else {
                    error("Please select item");
                }
            } else {
                error("Please select item");
            }
        }
    }

    List<Account> getAccountsList() {
        User user = PMSession.get().getAuthenticatedUser();
        return accountManager.getAccountsForUser(user);
    }

}
